package org.cy.evolution.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.cy.evolution.R;

public class ToastUtil {
    private static Toast toast;

    public static void uiShow(final Activity activity, final int msgId) {
        if (null != activity) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    show(activity, msgId);
                }
            });
        }
    }

    public static void uiShow(final Activity activity, final String msg) {
        if (null != activity) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    show(activity, msg);
                }
            });
        }
    }

    public static void show(Context context, int msgId) {
        final String msg = context.getResources().getString(msgId);
        show(context, msg);
    }

    public static void show(Context context, String msg) {
        show(context, msg, Toast.LENGTH_SHORT);
    }

    public static void show(Context context, int msgId, int duration) {
        final String msg = context.getResources().getString(msgId);
        show(context, msg, duration);
    }

    public static void show(final Context context, final String msg, final int duration) {
        if (null != context) {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                showToast(context, msg, duration);
            } else {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        showToast(context, msg, duration);
                    }
                });
            }
        }
    }

    private static void showToast(Context context, String msg, int duration) {
        if (null != context) {
            if (null == toast) {
                toast = new Toast(context);
                LayoutInflater inflater = LayoutInflater.from(context);
                View container = inflater.inflate(R.layout.layout_toast_custom, null);
                TextView tvMsg = container.findViewById(R.id.toast_custom_message);
                tvMsg.setText(msg);
                toast.setDuration(duration);
                toast.setView(container);
            } else {
                toast.setText(msg);
            }
            toast.show();
        }
    }
}
